let nodes = [{ id: 2, name: "2", pId: 0 },
{ id: 4, name: "4", pId: 2 },
{ id: 12, name: "12", pId: 2 },
{ id: 8, name: "8", pId: 4 },
{ id: 10, name: "10", pId: 4 },
]

//转为 打印a
let a = {
    id: 2,
    name: "2",
    pId: 0,
    children: [
        {
            id: 4,
            name: "4",
            pId: 2,
            children: [
                { id: 8, name: "8", pId: 4 },
                { id: 10, name: "10", pId: 4 }
            ]
        },
        { id: 12, name: "12", pId: 2 },
    ]
}

/**
 * 转换函数
 * @param {Array} arr 
 */
function convert(arr) {
    //外部父親
    const tree = arr.filter(parent => {
         const parentCopy = parent;//
        //  console.log(parentCopy);
         //返回每一项的子级数据
         const branchArr = arr.filter(child => parentCopy[id] === child[pId])
         if(branchArr.length > 0){
             parentCopy.children = branchArr;//存在子集,则给父添加children
         }
         return parentCopy.pId === 0;//返回第一层
    })

    return tree;
}

console.log("11",convert(nodes));
// convert(nodes)